<?php
/**
 *------------------------------------------------
 * Author: YYT[QQ:375776626]
 *------------------------------------------------
 */

abstract class Action extends Template
{
    public function display($template = '')
    {
        if (!$template) {
            $template = strtolower(substr(get_class($this), 0, -6));
            $action = get_called_method();
            if ($action != 'index') $template .= '-'.$action;
        }
        parent::display($template);
    }

    public static function isAjax()
    {
        if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
            if ('xmlhttprequest' == strtolower($_SERVER['HTTP_X_REQUESTED_WITH']))
                return true;
        }
        if (!empty($_GET['ajax'])) return true;
        return false;
    }

    public static function redirect($url, $time = 0)
    {
        $message = '系统将在 '.$time.' 秒之后自动跳转到 '.$url;
        if (!headers_sent()) {
            if ($time === 0) {
                header('Location:'.$url);
            } else {
                header('refresh:'.$time.';url='.$url);
                echo $message;
            }
        } else {
            $str = '<meta http-equiv=\'Refresh\' content=\''.$time.';URL='.$url.'\'>';
            if ($time > 0) $str .= $message;
            echo $str;
        }
        exit();
    }

    protected function success($success, $backUrls = '')
    {
        if (!$backUrls) $backUrls = array('返回上页' => $_SERVER['HTTP_REFERER']);
        $assign['title'] = '操作成功';
        $assign['success'] = $success;
        $assign['backUrls'] = $backUrls;
        $this->assign($assign);
        exit($this->fetch('success'));
    }

    protected function error($error, $backUrls = '')
    {
        if (!$backUrls) $backUrls = array('返回上页' => 'javascript:history.back(-1);');
        $assign['title'] = '操作失败';
        $assign['error'] = $error;
        $assign['backUrls'] = $backUrls;
        $this->assign($assign);
        exit($this->fetch('error'));
    }

    protected function tips($type, $tips, $template = '')
    {
        $this->assign($type, $tips);
        if ($template) echo $this->fetch($template);
    }

    protected function _404($template = '')
    {
        if (!$template) {
            header('HTTP/1.1 404 Not Found');
            exit();
        }
        exit($this->fetch($template));
    }
}

if (!function_exists('get_called_method')) {
    function get_called_method()
    {
        $backtrace = debug_backtrace();
        array_shift($backtrace);
        return $backtrace[1]['function'];
    }
}